# nacos/token_manager.py

import time
import logging
import requests
from Tools.scripts.generate_opcode_h import header

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 配置常量
NACOS_SERVER = "http://129.211.24.193:8848/nacos"
NACOS_USERNAME = "nacos"  # 填写你的 Nacos 用户名
NACOS_PASSWORD = "Liuwei19831022@"  # 填写你的 Nacos 密码
TOKEN_URL = f"{NACOS_SERVER}/v1/auth/users/login"  # 获取 token 的接口

# 用于存储和更新 token
current_token = None
token_expiry_time = 0

# 获取新的 Token
def get_new_token():
    global current_token, token_expiry_time
    login_payload = {
        "username": NACOS_USERNAME,
        "password": NACOS_PASSWORD
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }

    try:
        response = requests.post(TOKEN_URL, data=login_payload, headers=headers)
        if response.status_code == 200:
            token_data = response.json()
            current_token = token_data["accessToken"]
            expires_in = token_data.get("tokenTtl", 3600)  # Token 有效期（默认为 1 小时）
            token_expiry_time = time.time() + expires_in
            logger.info(f"New token obtained: {current_token}")
        else:
            logger.error(f"Failed to get token: {response.text}")
    except Exception as e:
        logger.error(f"Error getting token: {e}")

# 刷新 Token
def refresh_token_if_needed():
    global current_token, token_expiry_time
    if time.time() > token_expiry_time:
        logger.info("Token expired or near expiration, refreshing...")
        get_new_token()

# 获取当前 Token
def get_current_token():
    if current_token is None:
        logger.error("Token is not available.")
    return current_token
